#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>

/*
 * 一次唤醒一大批线程
 */


using namespace std;

int tickets = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* start_routine(void* args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        //判断省略
        cout<<name<<" -> "<<tickets<<endl;
        tickets--;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t t1,t2;
    pthread_t t[5];

    for(int i = 0;i<5;i++)
    {
        char*name = new char[64];
        snprintf(name,64,"thread %d",i+1);
        pthread_create(t+i,nullptr,start_routine,name);
    }

    while(true)
    {
        sleep(1);
        pthread_cond_broadcast(&cond);
        cout<<"main thread wakeup one thread..."<<endl;
    }

    for(int i = 0;i<5;i++)
    {
        pthread_join(t[i], nullptr);
    }

    return 0;
}

#if 0
thread 1 -> main thread wakeup one thread...1000

thread 2 -> 999
thread 4 -> 998
thread 3 -> 997
thread 5 -> 996
main thread wakeup one thread...
thread 5 -> 995
thread 1 -> 994
thread 3 -> 993
thread 4 -> 992
thread 2 -> 991
main thread wakeup one thread...
thread 3 -> 990
thread 5 -> 989
thread 4 -> 988
thread 2 -> 987
thread 1 -> 986
thread 5 -> 985
thread 3 -> main thread wakeup one thread...
984
thread 2 -> 983
thread 4 -> 982
thread 1 -> 981
#endif
